package com.yx.cloud.fragment;//package com.yx.cloud.fragment;
//
//import android.Manifest;
//import android.annotation.SuppressLint;
//import android.app.AppOpsManager;
//import android.bluetooth.BluetoothAdapter;
//import android.content.Intent;
//import android.content.pm.PackageManager;
//import android.os.Bundle;
//import android.util.Log;
//import android.view.LayoutInflater;
//import android.view.View;
//import android.view.ViewGroup;
//import android.widget.Button;
//import android.widget.Toast;
//
//import androidx.core.app.ActivityCompat;
//import androidx.core.app.AppOpsManagerCompat;
//import androidx.recyclerview.widget.LinearLayoutManager;
//import androidx.recyclerview.widget.RecyclerView;
//
//import com.aliyun.alink.business.devicecenter.api.add.DeviceInfo;
//import com.aliyun.alink.business.devicecenter.api.discovery.LocalDeviceMgr;
//import com.google.gson.Gson;
//import com.tuya.smart.android.ble.api.ScanDeviceBean;
//import com.yx.cloud.AppContext;
//import com.yx.cloud.BuildConfig;
//import com.yx.cloud.MyApplication;
//import com.yx.cloud.R;
//import com.yx.cloud.activity.AddEquipmentActivity;
//import com.yx.cloud.activity.AddEquipmentYinXingActivity;
//import com.yx.cloud.activity.BindTaobaoAccountActivity;
//import com.yx.cloud.activity.MainActivity;
//import com.yx.cloud.activity.MainActivity2;
//import com.yx.cloud.activity.SelectWIFIActivity;
//import com.yx.cloud.activity.TmallUnbindUserActivity;
//import com.yx.cloud.adapter.AddDevice_BluetoothListAdapter;
//import com.yx.cloud.base.LazyLoadFragment;
//import com.yx.cloud.constant.Constants;
//import com.yx.cloud.product.SweeperProductConfig;
//import com.yx.cloud.product.ProductManager;
//import com.yx.cloud.product.gyro.G5MAX;
//import com.yx.cloud.product.gyro.GD48;
//import com.yx.cloud.product.gyro.X1;
//import com.yx.cloud.product.laser.inxni.INXNIConstant;
//import com.yx.cloud.product.laser.inxni.X3;
//import com.yx.cloud.product.laser.inxni.X3S_P2P;
//import com.yx.cloud.product.laser.inxni.X3_PD35_61_P2P;
//import com.yx.cloud.product.laser.pd.G20;
//import com.yx.cloud.product.laser.zw.ZW2X;
//import com.yx.cloud.product.sdk.tmall.AliGenieSdk;
//import com.yx.cloud.utils.AppUtil;
//import com.yx.cloud.utils.Intent_utils;
//import com.yx.cloud.utils.RomUtils;
//import com.yx.cloud.utils.SharedPrefsUtil;
//import com.yx.cloud.utils.ToastUtil;
//import com.yx.cloud.utils.WifiAdmin;
//import com.iot.common.utils.Event;
//import com.yx.robot.product.Product;
//import com.yx.robot.sdk.req.BluetoothScanDeviceBean;
//import com.iot.common.utils.LogUtils;
//
//import org.json.JSONException;
//import org.json.JSONObject;
//
//import java.util.ArrayList;
//import java.util.List;
//import java.util.Map;
//
//import org.greenrobot.eventbus.EventBus;import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
//
//
//public class MenuAddDeviceFragment extends LazyLoadFragment {
//    private final static String TAG = "MenuAddDeviceFragment";
//    private int REQUEST_CODE_ASK_PERMISSIONS = 1;
//    private MainActivity2 activity;
//    private Button mBtnAddDevice;
//    private WifiAdmin wifiAdmin;
//    private MyApplication application;
//    private List<BluetoothScanDeviceBean> leeee = new ArrayList<>();
//    //蓝牙扫描结果存储
//    private BluetoothScanDeviceBean bsb;
//    private boolean ALi = false;
//    private RecyclerView mTmallDeviceList;
//    private AddDevice_BluetoothListAdapter abla;
//    private List<String> mPermissionList = new ArrayList<>();
//    private boolean hasPermissionDismiss = false, permission_2;
//    private int permission_1;
//    private String mTmall_userNickname;
//    private boolean bluetoothScanTag = false;
//    private BluetoothAdapter mBluetoothAdapter;
//    private boolean enable;
//    private boolean doesItExist = false;
//
//    @Override
//    public void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//        activity = (MainActivity2) getActivity();
//    }
//
//    @Override
//    protected int setContentView() {
//        return R.layout.menuadddevice_fragment;
//    }
//
//    @Override
//    public void onPageSelect(int position) {
//        super.onPageSelect(position);
//        LogUtils.i("AddFra " + position);
//        activity.binding.ivRightMenu.setVisibility(View.GONE);
//        initView();
//        initData();
//        SharedPrefsUtil.putValue(activity, Constants.DEVICEID, "deviceId", "555");
//    }
//
//    @Override
//    public void onPageUnselect(int position) {
//        super.onPageUnselect(position);
//        if (Constants.FLAVOR_INXNI.equals(BuildConfig.FLAVOR)) {
//            AppContext.getService().tuyaStopLeScan();
//            LocalDeviceMgr.getInstance().stopDiscovery();//天猫停⽌设备发现
//        } else if (Constants.FLAVOR_ICLEBO.equals(BuildConfig.FLAVOR)) {
//            AppContext.getService().tuyaStopLeScan();
//        }
//    }
//
//    @Override
//    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//        View view = super.onCreateView(inflater, container, savedInstanceState);
//        // initView();
//        // initData();
//        return view;
//    }
//
//    private void initView() {
//        Log.d(TAG, " : MenuAddDeviceFragment======initView========= : ");
//        application = (MyApplication) activity.getApplicationContext();
//        mBtnAddDevice = findViewById(R.id.btn_addDevice);
//        mTmallDeviceList = findViewById(R.id.tmall_bluetoothDeviceList);
//        mBtnAddDevice.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (RomUtils.isFastClick()) {
//                    return;
//                }
//                LocalDeviceMgr.getInstance().stopDiscovery();//天猫停⽌设备发现
//                if (EventBus.getDefault().isRegistered(activity)) {
//                    EventBus.getDefault().unregister(activity);
//                }
//                //添加设备
//                if (wifiAdmin == null) {
//                    wifiAdmin = new WifiAdmin(activity);
//                }
//                String checkState = wifiAdmin.checkState(activity);
//                if (checkState.equals("1")) {
//                    ToastUtil.show(activity, getString(R.string.open_wifi), Toast.LENGTH_LONG);
//                    return;
//                }
//                if (Constants.FLAVOR_INXNI.equals(BuildConfig.FLAVOR)) {
//                    Intent_utils.enterIntentMenu(activity, AddEquipmentActivity.class);
//                } else {
//                    Intent_utils.enterIntentMenu(activity, AddEquipmentYinXingActivity.class);
//                }
//                leeee.clear();
//                abla.notifyDataSetChanged();
//            }
//        });
//    }
//
//    private void initData() {
//        Log.d(TAG, " : MenuAddDeviceFragment======initData========= : ");
//        bluetoothScanTag = true;
//        int currentItem = activity.binding.mMainViewPager.getCurrentItem();
//        if (currentItem < AppContext.get().deviceListData_local.size() && Constants.ITEM_POSITION != currentItem) {
//            //设置机器信息
//            Constants.ITEM_POSITION = currentItem;
//        }
//        if (activity.firmware_dialog != null) {
//            if (activity.firmware_dialog.isShowing()) {
//                activity.firmware_dialog.dismiss();
//            }
//        }
//        activity.isMianShow = false;
//        activity.mMesListData.clear();//消息列表
//        activity.binding.mainMesList.setVisibility(View.GONE);//消息列表
//        if (Constants.UpdateLayout != null) {
//            Constants.UpdateLayout.setVisibility(View.GONE);//升级布局
//        }
//
//        tmallBluethoothScanInitialize();
//    }
//
//    private void tmallBluethoothScanInitialize() {
//        //天猫蓝牙扫描
//        int currentItem = activity.binding.mMainViewPager.getCurrentItem();
//        if (currentItem != AppContext.get().deviceListData_local.size()) {
//            return;
//        }
//        if (!EventBus.getDefault().isRegistered(this)) {
//            EventBus.getDefault().register(this);
//        }
//        Log.d(TAG, " : tmallBluethoothScanInitialize=============== : " + currentItem);
//        if (abla == null) {
//            abla = new AddDevice_BluetoothListAdapter(activity, leeee);
//            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(activity);
//            mTmallDeviceList.setLayoutManager(linearLayoutManager);
//            mTmallDeviceList.setAdapter(abla);
//            abla.notifyDataSetChanged();
//        }
//        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
//        openBluetooth();
//        tmallBluethoothScan();
//    }
//
//    private void tmallBluethoothScan() {
//        leeee.clear();
//        ALi = false;
//        if (abla == null) {
//            abla = new AddDevice_BluetoothListAdapter(activity, leeee);
//            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(activity);
//            mTmallDeviceList.setLayoutManager(linearLayoutManager);
//            mTmallDeviceList.setAdapter(abla);
//        }
//        abla.notifyDataSetChanged();
//        abla.setOnItemClickListener(new AddDevice_BluetoothListAdapter.OnItemClickListener() {
//            @Override
//            public void onItemClick(View v, int position) {
//                if (v.getId() == R.id.btn_startConfiguration) {
//                    LocalDeviceMgr.getInstance().stopDiscovery();//天猫停⽌设备发现
//                    Log.i(TAG, "点击了开始配置按钮 -------------------------》  :");
//                    SharedPrefsUtil.putValue(activity, "ROBOT_SERIES", "robot_series", "bluetooth");//给配网失败后返回使用
//                    BluetoothScanDeviceBean deviceBean = leeee.get(position);
//                    String source = deviceBean.getSource();//区分蓝牙扫描出来的设备 是X5 基站还是其他机型的
//                    if ("ali".equals(source)) {
//                        AppContext.get().setRobotType("X5");
//                        mTmall_userNickname = SharedPrefsUtil.getValue(activity, "TMALL_ALIGENIE_USER_INFO", "tmall_aligenie_user_info", "");
//                        INXNIConstant.TMALL_USER_NICK_NAME = mTmall_userNickname;
//                        //已经登录成功了，不在进行登录直接进行绑定
//                        if ("".equals(mTmall_userNickname)) {
//                            Intent select = new Intent(activity, BindTaobaoAccountActivity.class);
//                            select.putExtra("network", "bluetooth");
//                            select.putExtra("bluetoothData", deviceBean);
//                            startActivity(select);
//                        } else {
//                            Intent intent = new Intent(activity, TmallUnbindUserActivity.class);
//                            intent.putExtra("network", "bluetooth");
//                            intent.putExtra("source", "X5");
//                            intent.putExtra("nickname", INXNIConstant.TMALL_USER_NICK_NAME);
//                            intent.putExtra("bluetoothData", deviceBean);//保存的X5蓝牙信息
//                            startActivity(intent);
//                        }
//                    } else {
//                        Product product = ProductManager.getProductById(deviceBean.getProductId());
//                        String seriesName = ((SweeperProductConfig) product.getConfig()).productName;
//                        AppContext.get().setRobotType(seriesName);
//                        Intent select = new Intent(activity, SelectWIFIActivity.class);
//                        select.putExtra("network", "bluetooth");
//                        select.putExtra("source", "other");
//                        select.putExtra("bluetoothData", deviceBean);
//                        startActivity(select);
//                    }
//                }
//            }
//        });
//
//    }
//
//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void onMessageEvent(Event event) {
//        switch (event.getType()) {
//            case Event.MESSAGE_TYPE_TUYA_BLUETOOTH_SCAN:
//                //涂鸦蓝牙扫描回调 TODO:涂鸦内部已经做了重复过滤了
//                doesItExist = false;
//                ScanDeviceBean bean = (ScanDeviceBean) event.getContent();
//                LogUtils.d("涂鸦 event Bluetooth scan  :::::::::::::::::::::::::: " + new Gson().toJson(bean));
//                Product product = ProductManager.getProductById(bean.getProductId());
//                LogUtils.d(product + " : 涂鸦 event bean.getProductId()  :::::::::::::::::::::::::: " + bean.getProductId());
//                if (product == null) {
//                    return;
//                }
//                if (leeee.size() > 0) {
//                    for (int i = 0; i < leeee.size(); i++) {
//                        if (bean.getAddress().equals(leeee.get(i).getAddress())) {
//                            doesItExist = true;
//                        }
//                    }
//                }
//                if (!doesItExist) {
//                    String name = ((SweeperProductConfig) product.getConfig()).productName;
//                    LogUtils.d("涂鸦 event name  :::::::::::::::::::::::::: " + name);
//                    if (Constants.FLAVOR_INXNI.equals(BuildConfig.FLAVOR)) {
//                        //涂鸦蓝牙搜索时X5的机器不显示，只显示天猫精灵
//                        if (product == X3S_P2P.get() || product == X3.get() || product == X1.get() || product == X3_PD35_61_P2P.get()) {
//                            LogUtils.d("涂鸦 Bluetooth scan  :::::::::::::::::::::::::: " + new Gson().toJson(bean));
//                            scanDataPackage("tuya", bean, null);
//                            abla.notifyDataSetChanged();
//                        } else if ("X5".equals(name)) {
//                            //如果是x5的机器就存起来给配网使用 TODO:暂时没用到
//                            bsb = new BluetoothScanDeviceBean();
//                            bsb.setSource("tuya");
//                            bsb.setMac(bean.getMac());
//                            bsb.setAddress(bean.getAddress());
//                            bsb.setUuid(bean.getUuid());
//                            bsb.setFlag(bean.getFlag());
//                            bsb.setId(bean.getId());
//                            bsb.setName(bean.getName());
//                            bsb.setDeviceType(bean.getDeviceType());
//                            bsb.setProviderName(bean.getProviderName());
//                            bsb.setProductId(bean.getProductId());
//                            bsb.setConfigType(bean.getConfigType());
//                            AppContext.get().x5_bluetoothdeviceList.add(bsb);
//                        }
//                    } else if (Constants.FLAVOR_ICLEBO.equals(BuildConfig.FLAVOR)) {
//                        LogUtils.d("银星 涂鸦 event name  :::::::::::::::::::::::::: " + name);
//                        if (product == GD48.get() || product == G5MAX.get() || product == G20.get()) {
//                            LogUtils.d("涂鸦 Bluetooth scan  :::::::::::::::::::::::::: " + new Gson().toJson(bean));
//                            scanDataPackage("tuya", bean, null);
//                            if (abla != null) {
//                                abla.notifyDataSetChanged();
//                            }
//                        }
//                    } else if (Constants.FLAVOR_YINXING.equals(BuildConfig.FLAVOR)) {
//                        if (product == ZW2X.get()) {
//                            scanDataPackage("tuya", bean, null);
//                            if (abla != null) {
//                                abla.notifyDataSetChanged();
//                            }
//                        }
//                    }
//                }
//
//                break;
//            case Event.MESSAGE_TYPE_TMALL_BLUETOOTH_SCAN:
//                //天猫精灵蓝牙扫描回调
//                List<DeviceInfo> list = (List<DeviceInfo>) event.getContent();
//                LogUtils.d(leeee.size() + " :添加 阿里 Bluetooth scan  :::::::::::::::::::::::::: " + list.toString());
//                if (list.size() > 0) {
//                    if (leeee.size() == 0) {
//                        if (!ALi) {
//                            for (int j = 0; j < list.size(); j++) {
//                                DeviceInfo deviceInfo_j = list.get(j);
//                                scanDataPackage("ali", null, deviceInfo_j);
//                            }
//                            abla.notifyDataSetChanged();
//                        }
//                    } else {
//                        for (int ii = 0; ii < list.size(); ii++) {
//                            DeviceInfo info = list.get(ii);
//                            String mac1 = info.mac;
//                            for (int j = 0; j < leeee.size(); j++) {
//                                if (mac1.equals(leeee.get(j).getMac())) {
//                                    //说明已经存在了
//                                    ALi = true;
//                                }
//                            }
//                        }
//                        if (!ALi) {
//                            for (int iii = 0; iii < list.size(); iii++) {
//                                DeviceInfo deviceInfo_iii = list.get(iii);
//                                scanDataPackage("ali", null, deviceInfo_iii);
//                            }
//                            abla.notifyDataSetChanged();
//                        }
//                    }
//                }
//                break;
//        }
//    }
//
//    private void scanDataPackage(String source, ScanDeviceBean bean, DeviceInfo deviceInfo) {
//        LogUtils.d("阿里 scanDataPackage  :::::::::::::::::::::::::: ");
//        if (source.equals("tuya")) {
//            bsb = new BluetoothScanDeviceBean();
//            bsb.setSource("tuya");
//            bsb.setMac(bean.getMac());
//            bsb.setAddress(bean.getAddress());
//            bsb.setUuid(bean.getUuid());
//            bsb.setFlag(bean.getFlag());
//            bsb.setId(bean.getId());
//            bsb.setName(bean.getName());
//            bsb.setDeviceType(bean.getDeviceType());
//            bsb.setProviderName(bean.getProviderName());
//            bsb.setProductId(bean.getProductId());
//            bsb.setConfigType(bean.getConfigType());
//        } else {
//            bsb = new BluetoothScanDeviceBean();
//            bsb.setSource("ali");
//            bsb.setDeviceId(deviceInfo.deviceId);
//            bsb.setDeviceName(deviceInfo.deviceName);
//            bsb.setMac(deviceInfo.mac);
//            bsb.setProductId(deviceInfo.productId);
//            bsb.setProductKey(deviceInfo.productKey);
//            bsb.setUserId(deviceInfo.userId);
//            Map extraDeviceInfo = deviceInfo.getExtraDeviceInfo();
//            String info = getExtraDeviceInfo(extraDeviceInfo);
//            bsb.setExtraDeviceInfo(info);
//        }
//        leeee.add(bsb);
//    }
//
//    @SuppressLint("MissingPermission")
//    private void openBluetooth() {
//        //TODO 这里只检测该有的权限是否都有了不进行权限申请，如果有了才进行蓝牙扫描
//        if (!AppUtil.isLocServiceEnable(activity)) {//检测是否开启定位服务
//            //未开启定位服务的操作
//            LogUtils.i("--------------------------------未开启定位服务的操作");
//            // locatePermissionsDialog("locationInformation");
//        } else {
//            //检测用户是否将当前应用的定位权限拒绝
//            int checkResult = AppUtil.checkOp(activity, 2, AppOpsManager.OPSTR_FINE_LOCATION);//其中2代表AppOpsManager.OP_GPS，如果要判断悬浮框权限，第二个参数需换成24即AppOpsManager。OP_SYSTEM_ALERT_WINDOW及，第三个参数需要换成AppOpsManager.OPSTR_SYSTEM_ALERT_WINDOW
//            int permission2 = ActivityCompat.checkSelfPermission(activity, Manifest.permission.BLUETOOTH_SCAN);//蓝牙扫描或WIFI扫描时需要的附近设备权限
//            if (AppOpsManagerCompat.MODE_IGNORED == checkResult || permission2 != PackageManager.PERMISSION_GRANTED) {
//                //未开启定位权限或者被拒绝的操作
//                LogUtils.i("--------------------------------未开启GPS服务的操作");
//                // locatePermissionsDialog("GPS");
//            } else {
//                int blu_switch = ActivityCompat.checkSelfPermission(activity, Manifest.permission.BLUETOOTH_CONNECT);
//                if (blu_switch != PackageManager.PERMISSION_GRANTED) {
//                    LogUtils.i("--------------------------------未开启蓝牙");
//                } else {
//                    //所以权限都有了
//                    LogUtils.i("--------------------------------所以权限都有了");
//                    AppContext.getService().tuyaBluetoothScan();//涂鸦 开始蓝牙扫描
//                    if (Constants.FLAVOR_INXNI.equals(BuildConfig.FLAVOR)) {
//                        AliGenieSdk.tmallBluetoothScan(activity);//阿里 开始蓝牙扫描
//                    }
//                }
//            }
//        }
//
//    }
//
//    private String getExtraDeviceInfo(Map extraDeviceInfo) {
//        String json = new Gson().toJson(extraDeviceInfo);
//        JSONObject jsonObject = null;
//        String netConfigFlag;
//        try {
//            jsonObject = new JSONObject(json);
//            JSONObject object = jsonObject.getJSONObject("ble_discovered_device");
//            netConfigFlag = object.getString("netConfigFlag");
//            // if ("iLHk".equals(netConfigFlag)) {
//        } catch (JSONException e) {
//            throw new RuntimeException(e);
//        }
//        return netConfigFlag;
//    }
//
//    @Override
//    public void onStop() {
//        super.onStop();
//        LogUtils.i(" onStop :");
//    }
//}
